<template>
  <div class="assignment-header">
    <button class="back-button" @click="goBack"><img src="@/assets/svgs/left.svg" alt="Back" /></button>
  </div>
  <div v-if="details" class="detail">
    <div class="detail_head">
      <p class="aler1">作业详情<span class="Xcancle" @click="viewHomeworkCancle">X</span></p>
    </div>
    <div class="assignment-grading">
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(item, index) in assignment" :key="item.studentAnswerId" :name="index">
          <template #title>
            <h2 class="aler2">题目 {{ index + 1 }}: {{ item.question }}</h2>
          </template>
          <p class="aler3">学生答案: {{ item.answer }}</p>
          <p class="aler3">标准答案: {{ item.standardAnswer }}</p>
          <p class="aler3">得分: {{ item.score !== null ? item.score : '未批改' }}</p>
          <p class="aler3">评语: {{ item.comment }}</p>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
  <div style="width: 100%;height: 90%;">
    <table class="homework_table">
      <thead class="homework_head">
        <tr>
          <th>顺序</th>
          <th>姓名</th>
          <th>提交时间</th>
          <th>得分</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr class="homework_tr" v-for="(student, index) in students" :key="student.userId">
          <td>{{ index + 1 }}</td>
          <td>{{ student.userName }}</td>
          <td>{{ student.submitTime }}</td>
          <td> <!-- 根据 totalScore 的值动态显示内容 -->
            <span v-if="student.totalScore === -1" style="color: red;">未批改</span>
            <span v-else>{{ student.totalScore }}</span>
          </td>
          <td>
            <span @click="handleCorrectHomeworkClick(student.userId)" class="viewHomeworks">老师批改</span>
            <span @click="viewHomework(student.userId)" class="viewHomeworks">查看作业</span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getHomeworkByIdService, getStuAnswerService } from '@/api/homework';

const router = useRouter();
const details = ref(false);
const goBack = () => {
  router.push('/teacher/assignment/card');
};

//获取作业id
const route = useRoute(); // 获取当前路由对象
const homeworkId = ref(null);
homeworkId.value = route.params.homeworkId; // 从路由参数中获取 homeworkId
console.log("获取到的作业Id:", homeworkId.value);


// 获取作业详情
const resulthomework = async () => {
  try {
    const response = await getHomeworkByIdService(homeworkId.value);
    if (response && response.data) {
      // 在获取数据后动态创建 students 容器
      const students = response.data.map(item => ({
        userId: item.userId,          // 用户 ID
        userName: item.userName,      // 用户姓名
        submitTime: item.submitTime,  // 提交时间
        totalScore: item.totalScore   // 总得分
      }));

      console.log("后端返回的学生数据:", students);

      // 返回 students 数据供模板使用
      return students;
    } else {
      ElMessage.error("未获取到作业数据");
      return []; // 返回空数组
    }
  } catch (err) {
    ElMessage.error(`获取作业内容失败，请稍后再试: ${err.message}`);
    console.error('Error:', err);
    return []; // 返回空数组
  }
};

// 调用获取作业详情，并存储返回的数据
const students = ref([]); // 使用 ref 来存储获取到的数据
resulthomework().then(data => {
  students.value = data; // 将获取到的数据赋值给 students
});

const assignment = ref([]); // 存储作业详情数据

const viewHomework = async (userId) => {
  console.log("请求的 userId:", userId, "homeworkId:", homeworkId.value);

  if (isNaN(Number(userId)) || isNaN(Number(homeworkId.value))) {
    ElMessage.error("Invalid userId or homeworkId");
    return;
  }

  try {
    const response = await getStuAnswerService(homeworkId.value, userId);
    if (response && response.data) {
      assignment.value = response.data; // 存储后端返回的所有数据
      details.value = true; // 显示作业详情模块
    } else {
      ElMessage.error("未获取到作业详情数据");
    }
  } catch (err) {
    ElMessage.error(`获取作业详情失败: ${err.message}`);
  }
};

const activeNames = ref(); // 默认不展开个面板


const homeworkData = ref({
  homeworkId: null,
  userId: students.value.userId,
});

// 从路由参数中获取 homeworkId
homeworkData.value.homeworkId = route.params.homeworkId;
console.log("获取到的作业Id:", homeworkData.value.homeworkId);

const handleCorrectHomeworkClick = (userId) => {
  console.log('handleCorrectHomeworkClick 被调用，homeworkId:', homeworkData.value.homeworkId, 'userId:', userId);

  if (!homeworkData.value.homeworkId || !userId) {
    console.error('homeworkId 或 userId 无效:', homeworkData.value.homeworkId, userId);
    ElMessage.error('无效的作业ID或用户ID');
    return;
  }

  console.log('准备跳转到路径:', `/teacher/assignment/correct_homework`);

  router.push({
    path: `/teacher/assignment/correct_homework`,
    query: { homeworkId: homeworkData.value.homeworkId, userId } // 使用 query 参数传递
  }).then(() => {
    console.log('路由跳转成功');
  }).catch(err => {
    console.error('路由跳转失败:', err);
    ElMessage.error('页面跳转失败');
  });
};
const viewHomeworkCancle = () => {
  details.value = false;
};
</script>

<style scoped>
.assignment-header {
  display: flex;
  justify-content: space-between;
  height: 7lvh;
  align-items: center;
  background-color: #13227A;
  color: white;
}

.back-button {
  background-color: transparent;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 16px;
}


.homework_table {
  width: 96%;
  margin-left: 2%;
  border-collapse: collapse;
}

.homework_head {
  height: 80px;
  padding: 8px;
}

.homework_tr {
  height: 50px;
  margin-top: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ddd;
  border-radius: 5%;
}

.homework_tr td {
  padding: 8px;
  text-align: center;
}

.viewHomeworks {
  margin-left: 4px;
  color: rgb(46, 16, 218);
  cursor: pointer;
}

.viewHomeworks:hover {
  color: rgb(237, 16, 16);
}

.detail {
  position: absolute;
  top: 10%;
  left: 10%;
  width: 80lvw;
  height: 80lvh;
  background-color: rgb(238, 235, 235);
  border: 1px solid #cccccc;
  z-index: 999;
  display: cloumn;
}

.detail_head {
  float: left;
  height: 8lvh;
  width: 80lvw;
  background-color: #13227A;
}

.aler1 {
  color: #ffffff;
  font-size: 20px;
  font-weight: bold;
  margin-left: 45%;
  margin-top: 1%;
}


.Xcancle {
  color: #ffffff;
  float: right;
  margin-right: 3%;
}

.Xcancle:hover {
  color: #ff0202;
  cursor: pointer;
}


.assignment-grading {
  float: left;
  width: 80lvw;
  height: 72lvh;
  max-height: 72lvh;
  overflow-y: auto;
}

.aler2 {
  color: #333;
  margin-left: 2%;
}

.aler3 {
  font-size: 16px;
  line-height: 1.6;
  margin-top: 10px;
  margin-bottom: 20px;
  color: #666;
  margin-left: 5%;
}

.el-button {
  display: flex;
  position: fixed;
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  background-color: #132ec5;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.el-button:hover {
  background-color: #2b6aff;
}
</style>